package server;


import java.io.*;
import java.net.*;

public class SendThread extends Thread{
		
	Socket connectionSocket ;
	DataOutputStream outToClient ;
	int index;
	Buffer[] buffers;
	
	public SendThread(Socket connectionSocket_var, int index_var, Buffer[] b) throws IOException{
//		System.out.println("\nnew SendThread for host" + connectionSocket_var.getInetAddress());
		connectionSocket = connectionSocket_var;		
		outToClient = 
			new DataOutputStream(connectionSocket.getOutputStream());
		index = index_var;
		buffers = b;
	}
	
	public void run(){
		int i = 0;
		synchronized (buffers) {
			try{				
				while(true){
	//				String msgToClient = "Server's thread "+ this.getId() +" is in loop_" + i + '\n';
	//				outToClient.writeBytes(msgToClient);
	//				Server.buffers[index].queue.add(msgToClient);
					
					if(i > 10000){
						i = 0; //reset i
					}
					
					//Scan buffers
					String msgToClient = buffers[index].queue.remove();
					outToClient.writeBytes(msgToClient);				
					System.out.println("Have just sent " + msgToClient + " to " + connectionSocket.getInetAddress() + " i=" + i);
					i++;
						
					Thread.sleep(100);
				}					
			
			}
			catch (Exception e) {}
		}
	}

}
